
#include "gd32f30x.h"
#include "BSP_BLE.h"
#include "fifo.h"
#include "bsp_uart.h"
#include "bsp_delay.h"

static uint8_t bleRxBuffer[256];
static fifo_t bleRxFifo = {
	.buffer = bleRxBuffer,
	.size = sizeof(bleRxBuffer),
};

bool BSP_BLE_is_connect(void)
{
	return BLE_CON_GET() ? true : false;
}

void BSP_BLE_Reset(void)
{
	BLE_RST_SET();
	BSP_Delay_ms(500);
	BLE_RST_CLR();
}

void BSP_BLE_Callback(uint8_t rx)
{
	Fifo_PutOne(&bleRxFifo, &rx);
}

/*
BLE 模块硬件初始化
*/
void BSP_BLE_Init(void){
	//Fifo_Init(&bleRxFifo, bleRxBuffer, sizeof(bleRxBuffer));
	gpio_init(BLE_RST_PORT,GPIO_MODE_OUT_PP,GPIO_OSPEED_MAX,BLE_RST_PIN);
	gpio_init(BLE_CON_PORT,GPIO_MODE_IPU,GPIO_OSPEED_MAX,BLE_CON_PIN);
	BSP_BLE_Reset();
}

/*
清楚蓝牙串口通信缓存
*/
void BSP_BLE_ClearBuffer(void){
	Fifo_Clean(&bleRxFifo);
}

/*
发送1字节到蓝牙模块
*/
void BSP_BLE_SendByte(uint8_t ch){
//		BSP_Uart_Send(ch);
	uint32_t count = 0;

	while (RESET == usart_flag_get(BLE_USART_PORT, USART_FLAG_TC)){
		if(++count > 1000000)
			break;
	}
	
	usart_data_transmit(BLE_USART_PORT, ch);
}

/*
发送一串数据到蓝牙模块
*/
void BSP_BLE_SendBuf(uint8_t buf [ ], uint32_t len){
	uint32_t i;

	for(i = 0; i < len; ++i){
		BSP_BLE_SendByte(buf[i]);
	}
}

/*
从蓝牙模块接收1字节，等待timeout 毫秒。
成功返回接收到的数据，失败返回-1
*/
int BSP_BLE_ReceiveByte(uint32_t timeout){
	uint32_t t = timeout;
	uint8_t rx;
	
	while(Fifo_GetOne(&bleRxFifo, &rx) == 0){
		if(t == 0){
			return -1;
		}
		--t;
		BSP_Delay_ms(1);
	}
	return rx;
}

/*
从蓝牙模块接收1字节，异步不等待。
成功返回接收到的数据，失败返回-1
*/
int BSP_BLE_ReceiveByteAsync(void){
	uint8_t rx;	
	int ret = Fifo_GetOne(&bleRxFifo, &rx);
	if(ret){
		return rx;
	}
	return -1;
}



